﻿using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;

public class ResourcesTools {
	// === Public =====================================================================================================
	public static ResourcesTools CreateInstance() {
		var instance = new ResourcesTools();
		return instance;
	}

	public Object GetObjectFromResources(string path) {
		return GetObjectFromResources<Object>(path);
	}

	public T GetObjectFromResources<T>(string path) where T : Object {
		var objects = Resources.Load<T>(path);
		if (objects == null) {
			throw new ArgumentNullException(path);
		}
		return objects;
	}

	public List<T> GetObjectsFromResources<T>(string path) where T : Object {
		var objects = Resources.LoadAll<T>(path);
		if (objects == null) {
			throw new ArgumentNullException(path);
		}
		return new List<T>(objects);
	}

	public string GetTexturePath(Texture texture) {
		var texturePath = AssetDatabase.GetAssetPath(texture);
		if (texturePath == null) {
			return null;
		}
		texturePath = Tools.FileName.RemoveExtension(texturePath);
		var index = IndexOfAfterResource(texturePath);
		return index == -1 ? null : texturePath.Substring(index);
	}

	// === Private ====================================================================================================
    private static int IndexOfAfterResource(string path) {
	    if (string.IsNullOrEmpty(path)) {
		    return -1;
	    }
        var resourcePos = path.LastIndexOf(ResourceConstants.RESOURCE_PATH, StringComparison.Ordinal);
	    if (resourcePos != -1) {
		    return resourcePos + ResourceConstants.RESOURCE_PATH.Length;
	    }
	    return resourcePos;
    }
}